import store from '@/store'

const allPermission = "*:*:*";
const adminRole = "admin";

/**
 * 字符权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function hasPerms(value) {

  if(!validPermiValue(value)){
    return false;
  }

  let permissionDatas = value;
  if(typeof value === 'string'){
    if(value.indexOf(',')>-1){
      permissionDatas = value.split(',')
    }else{
      permissionDatas = [value];
    }
  }
  
  const permissions = store.getters && store.getters.permissions
  return permissions.some(permission => {
    return allPermission === permission || permissionDatas.includes(permission)
  });
}

/**
 * 角色权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function hasRole(value) {

  if(!validPermiValue(value)){
    return false;
  }

  let roleDatas = value;
  if(typeof value === 'string'){
    if(value.indexOf(',')>-1){
      roleDatas = value.split(',')
    }else{
      roleDatas = [value];
    }
  }

  const roles = store.getters && store.getters.roles
  return roles.some(role => {
    return adminRole === role || roleDatas.includes(role)
  });
}

export function validPermiValue(value){
  return value && (typeof value === 'string' || ((value instanceof Array && value.length)));
}
